<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/user'

import {
  detailApi,
  recordsApi,
  changeShopApi,
  type recordType,
  type cardType,
  type shopType
} from '@/api/info'
import { ElMessage } from 'element-plus'

import { useRoute, useRouter } from 'vue-router'
import Edit from '@iconify-icons/ep/edit'
import Switch from '@iconify-icons/ep/switch'
ElMessage.success('detail page load')

const route = useRoute()
const router = useRouter()
function toChangePhone() {
  router.push({ path: '/bind', query: { id: useUserStore().id } })
}
const loading = ref(false)
const recordLoading = ref(false)
const noMore = ref(false)
var page = 0
function moreRecords() {
  if (recordLoading.value) {
    return
  }
  console.log('moreRecords')
  recordLoading.value = true
  recordsApi({
    id: detail.userId,
    page: page
  })
    .then((res) => {
      recordLoading.value = false
      if (res.status != 200) {
        ElMessage.error(res.message)
        return
      }
      const { data } = res
      if (data.length == 0) {
        noMore.value = true
        return
      }
      records.value = records.value.concat(data)
      page++
    })
    .catch((err) => {
      ElMessage.error(err.message)
      recordLoading.value = false
    })
}
const records = ref<recordType[]>([])
const cards = ref<cardType[]>([])
const shops = ref<shopType[]>([])
const fail = ref(false)
const detail = reactive({
  userId: '',
  remain: 0,
  total: 0,
  discount: 100,
  pwd: '无',
  points: 0,
  birthday: '无',
  shopName: '',
  shopId: '',
  shopAddress: '',
  shopContact: '',
  expire_time: '无',
  recharge_time: '',
  create_time: '',
  consume_time: '',
  phone: ''
})
function getData() {
  ElMessage('getData')

  loading.value = true
  fail.value = false
  detailApi()
    .then((res) => {
      ElMessage.success('getData success')

      loading.value = false
      if (res.status != 200) {
        ElMessage.error(res.message)
        fail.value = true
        return
      }
      fail.value = false
      const { data } = res
      detail.remain = data.remain
      detail.total = data.total
      detail.discount = data.discount
      detail.pwd = data.pwd
      detail.points = data.points
      detail.birthday = data.birthday
      cards.value = data.cards
      detail.shopName = data.shopName
      detail.shopAddress = data.shopAddress
      detail.shopContact = data.shopContact
      detail.expire_time = data.expire_time
      detail.recharge_time = data.recharge_time
      detail.create_time = data.create_time
      detail.consume_time = data.consume_time
      detail.phone = data.phone
      detail.userId = data.userId
      detail.shopId = data.shopId
      shops.value = data.shops
      loading.value = false
      moreRecords()
    })
    .catch((error) => {
      ElMessage.error(error.message)
      loading.value = false
      fail.value = true
    })
}

getData()
const scrollContainer = ref<{
  scrollTop: number
  clientHeight: number
  scrollHeight: number
}>()
const handleScroll = (event: Event) => {
  console.log('handleScroll')
  if (scrollContainer.value!.scrollTop === 0 || noMore.value) {
    return
  }
  if (
    scrollContainer.value!.scrollTop + scrollContainer.value!.clientHeight >=
    scrollContainer.value!.scrollHeight
  ) {
    moreRecords()
    console.log('output-> 到达底部，加载更多数据')
  }
}
function toRecord(id: string) {
  router.push({ path: '/record', query: { id: id } })
}

function toChangeShop(id: string) {
  console.log(id)
  if (id == detail.shopId) {
    return
  }
  loading.value = true
  changeShopApi({
    shopId: id
  })
    .then((res) => {
      loading.value = false
      if (res.status != 200) {
        ElMessage.error(res.message)
        return
      }
      ElMessage.success(res.message)
      getData()
    })
    .catch((error) => {
      loading.value = false
      ElMessage.error(error.message)
    })
}
</script>

<template>
  <div v-loading="loading">
    <div v-if="fail">
      <el-empty description="信息获取失败">
        <div>
          <div class="btn_error">
            <el-button class="btn" type="primary" @click="getData">重试</el-button>
          </div>
          <div class="btn_error">
            <el-button class="btn" @click="toChangePhone">绑定其他手机号</el-button>
          </div>
        </div>
      </el-empty>
    </div>
    <div
      ref="scrollContainer"
      @scroll="handleScroll"
      style="height: 100vh; overflow-y: auto"
      class="content"
      v-else
    >
      <div class="top_container">
        <div class="flex" @click="toChangePhone">
          <div style="margin-right: 4px">
            {{ detail.phone }}
          </div>
          <IconifyIconOffline :icon="Edit" color="var(--el-color-primary)" width="24" />
        </div>
        <el-dropdown>
          <div class="flex">
            <div style="margin-right: 4px">
              {{ detail.shopName }}
            </div>
            <IconifyIconOffline :icon="Switch" color="var(--el-color-primary)" width="24" />
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="item in shops"
                :key="item.shopId"
                @click="toChangeShop(item.shopId)"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="container">
        <div class="line"><span class="des">店铺地址：</span>{{ detail.shopAddress ?? '无' }}</div>
        <div class="line"><span class="des">联系方式：</span>{{ detail.shopContact ?? '无' }}</div>
      </div>
      <div class="container">
        <div class="flex">
          <div class="half">
            <div class="line"><span class="des">当前余额：</span>{{ detail.remain }}元</div>
            <div class="line"><span class="des">累计充值：</span>{{ detail.total }}元</div>
            <div class="line"><span class="des">有效期限：</span>{{ detail.expire_time }}</div>
          </div>
          <div class="half">
            <div class="line"><span class="des">会员折扣：</span>{{ detail.discount }}</div>
            <div class="line"><span class="des">消费密码：</span>{{ detail.pwd ?? '无' }}</div>
            <div class="line"><span class="des">会员积分：</span>{{ detail.points ?? 0 }}</div>
          </div>
        </div>
      </div>
      <div class="container">
        <div class="flex">
          <div class="half">
            <div class="line"><span class="des">会员生日：</span>{{ detail.birthday }}</div>
            <div class="line"><span class="des">最近消费：</span>{{ detail.consume_time }}</div>
          </div>
          <div class="half">
            <div class="line"><span class="des">开通时间：</span>{{ detail.create_time }}</div>
            <div class="line"><span class="des">最近充值：</span>{{ detail.recharge_time }}</div>
          </div>
        </div>
      </div>
      <div class="container" v-if="cards.length > 0">
        <div class="des">服务次卡</div>
        <div class="h_list_container">
          <div v-for="card in cards" class="card_container">
            <div class="card_top_container">
              项目：
              <p style="color: #333333; margin-right: 6px">{{ card.name }}</p>
              次数：
              <p style="color: #333333; font-weight: bold">{{ card.value }}</p>
            </div>
            有效期：{{ card.expire_time }}
          </div>
        </div>
      </div>
      <!-- <div class="container" style="overflow: auto; height: 340px"> -->
      <div class="container">
        <div class="des" style="margin-bottom: 8px">消费记录</div>
        <div>
          <div @click="toRecord(record._id)" v-for="record in records" class="record_container">
            <div class="record_line">
              <div>
                {{ record.title }}
              </div>
              <div class="des">
                {{ record.create_time }}
              </div>
            </div>
            <div class="des">
              {{ record.des }}
            </div>
          </div>
        </div>
        <div class="list_bottom_text" v-if="recordLoading">加载中...</div>
        <div class="list_bottom_text" v-if="noMore">没有更多了</div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.content {
  background-color: #f9fafb;
}
.btn_error {
  width: 200px;
  margin-bottom: 20px;
}
.btn {
  width: 100%;
}
.top_container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  font-size: 18px;
  background-color: white;
}
.flex {
  display: flex;
  align-items: center;
}
.half {
  flex: 1;
}
.container {
  padding: 16px;
  margin-top: 8px;
  font-size: 16px;
  background-color: white;
}
.line {
  margin-top: 12px;
}
.title {
  font-size: 20px;
}
.des {
  color: var(--lowattention);
}

.h_list_container {
  display: flex;
  margin-top: 8px;
  /* flex-wrap:nowrap; */
  overflow-x: auto;
  white-space: nowrap;
}

::-webkit-scrollbar {
  display: none;
}

.card_container {
  padding-top: 6px;
  padding-bottom: 6px;
  margin-right: 6px;
  padding-left: 8px;
  padding-right: 8px;
  border: 1px solid #e5e6e7;
  text-align: left;
}
.card_top_container {
  margin-bottom: 4px;
  align-items: center;
  display: flex;
}
.record_container {
  height: 64px;
  margin-bottom: 4px;
  padding-top: 7px;
}

.record_line {
  display: flex;
  justify-content: space-between;
  margin-top: 6px;
}

.list_bottom_text {
  text-align: center;
  margin-top: 6px;
  color: var(--lowattention);
}
</style>
